package com.qy.securitydemo.controller;

import com.qy.securitydemo.model.SysUser;
import com.qy.securitydemo.util.Msg;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.security.Principal;

/**
 * @author HXB
 * @Title:
 * @Package
 * @Description:
 * @date 2019-11-0811:27
 */
@Controller
public class HomeController {

    //1，用户登录；
    //
    //2，根据用户ID，获取当前用户所拥有的所有权限；
    //String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().getUserId();
    //3，把权限放到session中；
    //
    //4，显示用户所拥有的资源。

    @RequestMapping("/")
    public String index(Model model) {
        SecurityContext sc = SecurityContextHolder.getContext();
        String username = getCurrentUsername();

        Msg msg = new Msg("测试标题-"+username, "测试内容", "额外信息，只对管理员显示");
        model.addAttribute("msg", msg);
        return "index";
    }

    public String getCurrentUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }
        if (principal instanceof Principal) {
            return ((Principal) principal).getName();
        }
        return String.valueOf(principal);
    }

}
